package design.createModel.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author wenhao hu
 * @title: TestBroke
 * @projectName design
 * @description: TODO
 * @date 2022/2/1814:52
 */
public class TestBroke {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        //serialBroke();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    reflectBroke();
                }
            } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    reflectBroke();
                }
            } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * @description: 序列化破坏单例模式
     * @author wenhao hu
     * @date 2022/2/18 14:52
     */
    public static void serialBroke() throws IOException, ClassNotFoundException {
        //获取对象
        LazySingleton lazySingleton = LazySingleton.getInstance4();
        //创建文件输出流对象
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("a.txt"));
        objectOutputStream.writeObject(lazySingleton);
        objectOutputStream.close();

        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("a.txt"));
        LazySingleton singleton = (LazySingleton) objectInputStream.readObject();
        objectInputStream.close();

        System.out.println(singleton == lazySingleton);
    }

    public static void reflectBroke() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取类
        Class<LazySingleton> clazz = LazySingleton.class;
        //获取无参构造
        Constructor<LazySingleton> constructor = clazz.getDeclaredConstructor();
        //取消访问检查
        constructor.setAccessible(true);
        //创建对象
        LazySingleton singleton1 = constructor.newInstance();
        LazySingleton singleton2 = constructor.newInstance();

        System.out.println("singleton1 = " + singleton1);
        System.out.println("singleton2 = " + singleton2);
        System.out.println(singleton1 == singleton2);
    }

}
